package com.asia.uploadfile;

import java.io.*;

import com.asia.special.CreateSQL;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {
	private String title;
	private File upload;
	private String uploadContentType;
	private String uploadFileName;
	private String allowTypes;
	private String savePath;

	public void setSavePath(String value) {
		this.savePath = value;
	}

	private String getSavePath() throws Exception {
		return ServletActionContext.getServletContext().getRealPath("/src/main/webapp/upload");
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getTitle() {
		return (this.title);
	}

	public File getUpload() {
		return (this.upload);
	}

	public String getUploadContentType() {
		return (this.uploadContentType);
	}

	public String getUploadFileName() {
		return (this.uploadFileName);
	}

	@Override
	public String execute() throws Exception {
		System.out.println("��ʼ�ϴ������ļ�---");
		System.out.println(getSavePath());
		System.out.println("==========" + getUploadFileName());
		System.out.println("==========" + getUploadContentType());
		System.out.println("==========" + getUpload());

		FileOutputStream fos = new FileOutputStream(getSavePath() + "\\"
				+ getUploadFileName());
		FileInputStream fis = new FileInputStream(getUpload());
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = fis.read(buffer)) > 0) {
			fos.write(buffer, 0, len);
		}
		if(fis!=null){
            try {
            	fis.close();
            	fis=null;
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }
		if(fos!=null){
            try {
            	fos.close();
            	fos=null;
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }
		CreateSQL createsql = new CreateSQL();
		if (SUCCESS.equals(createsql.CreateSQLfun())) {
			return SUCCESS;
		}else {
			return "false";
		}
		
	}

	public String filterType(String[] types) {
		String fileType = this.getUploadContentType();
		for (String type : types) {
			if (type.equals(fileType)) {
				return null;
			}
		}
		return INPUT;
	}

	public String getAllowTypes() {
		return "csv";
	}

	public void setAllowTypes(String allowTypes) {
		this.allowTypes = allowTypes;
	}
}